import { PureComponent } from 'react';
import { isNull } from '../../utils/request';
import { calcField, filterTemplate } from '../../utils/helper';
import MAction from '../MAction/MAction';
import moment from 'moment';

interface Props {
  config?: {
    [k: string]: any
  },
  template?: string,
  componentStyle?: object,
  formData?: object,
  event_key?: string,
  format?: any,
  list?: any,
  dataset_key?: any,
  [k: string]: any
}
interface State {
  [K: string]: any;
}
export default class MiCurrentTime extends PureComponent<Props, State> {
  timer: any = null;
  constructor(props) {
    super(props);
    this.state = {
      current_time: moment()
    }
  }
  componentWillMount() {
    this.timer = setInterval(() => {
      this.setState({
        current_time: moment()
      })
    }, 1000)
  }
  render() {
    let { current_time } = this.state;
    let { config = {}, template, componentStyle, formData, format, list, dataset_key } = this.props;
    if (!isNull(dataset_key) && list instanceof Array) {
      return null;
    }
    if (isNull(format)) {
      format = "YYYY-MM-DD HH:mm:ss"
    }
    list = {
      ...formData,
      ...list,
      _current_time: current_time.format(format)
    }
   
    if (!isNull(template)) {
      return <div style={componentStyle} dangerouslySetInnerHTML={{ __html: filterTemplate(template, list) }} onClick={() => {
        MAction({ ...this.props, formData: list }, this.props.event_key)
      }}></div>
    }
    return (
      <div>
        {list._current_time}
      </div>
    )
  }
  componentWillUnmount() {
    clearInterval(this.timer);
  }
}